//
//  SSTableViewCell.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/2/14.
//

import UIKit

class SSHomeTableViewCell: UITableViewCell {
    ///标题
    @IBOutlet weak var titleLab: UILabel!
    ///价格
    @IBOutlet weak var priceLab: UILabel!
    ///详情
    @IBOutlet weak var detailBtn: UIButton!
    ///描述
    @IBOutlet weak var describeLab: UILabel!
    ///头像
    @IBOutlet weak var portraitImgV: UIImageView!
    
    @IBOutlet weak var addLab: UILabel!
    ///规格
    @IBOutlet weak var specLab: UILabel!
    //线
    @IBOutlet weak var lineView: UIView!
    var model: ListCombo = ListCombo()
    var rootName:String = ""
    var type:String = ""
    
    @IBOutlet weak var coverBtn: UIButton!
    
    @IBOutlet weak var titleLabTopMargin: NSLayoutConstraint!
    //加减按钮
    @IBOutlet weak var numberBtn: PPNumberButton!
    
   
    
    override func awakeFromNib() {
        super.awakeFromNib()
        selectionStyle = .none
        //图片
        portraitImgV.layer.cornerRadius = 4
        portraitImgV.layer.masksToBounds = true
        detailBtn.contentHorizontalAlignment = .left
        //添加点击按钮
        addLab.layer.masksToBounds = true
        addLab.layer.cornerRadius = 4
        addLab.layer.borderColor = UIColor.init(hex: "5C3BEE")?.cgColor
        addLab.layer.borderWidth = 1
        addLab.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(clickAction(_:)))
        addLab.addGestureRecognizer(tap)
        numberBtn._maxValue = 9
        //+-回调
        numberBtn.numberResult{ (number,isAdd) in
            if !kIsLogin {
                kNotifiDefault.post(name: .AppShowLoginController, object: nil)
                return
            }
            if (self.model.isSpecs == "0"){//有规格
                if(!isAdd){//-
                    self.numberReduce(number: number)
                    return
                }
                //+
                let vc = SSProjectSpecificationController.init(nibName: "SSProjectSpecificationController", bundle: nil)
                vc.headerModel = self.model
                vc.type = self.type
                vc.numberResult { (spec) in
                    let number = Int(self.numberBtn.textField.text!)! + 1;
                    self.numberBtn.textField.text = "\(number)"
                    self.setSpecData(number: spec as Array<AnyObject>)
                }
                UIViewController.current().present(vc, animated: true)
            }else{//没规格
                if(!isAdd){//-
                    self.numberReduce(number:number)
                    return
                }
                //+
                let number = Int(self.numberBtn.textField.text!)! + 1;
                self.numberBtn.textField.text = "\(number)"
                var dicM = self.getItemDic()
                dicM["totalFee"] = stringToFloat(str: self.model.fee) as AnyObject
                self.saveShopingCart(dic: dicM)
                //总价格
//                self.saveTotalFee(fee: stringToFloat(str: self.model.fee))
            }
        }
    }
    
    //“添加”点击方法
    @objc func clickAction(_ tap: UITapGestureRecognizer){
        if !kIsLogin {
            kNotifiDefault.post(name: .AppShowLoginController, object: nil)
            return
        }
        if (model.isSpecs == "0"){//有规格
            let vc = SSProjectSpecificationController.init(nibName: "SSProjectSpecificationController", bundle: nil)
            vc.type = type
            vc.headerModel = model
            vc.numberResult { (number) in
                print("\(number)")
                self.setNumberValue()
                self.setSpecData(number: number as Array<AnyObject>)
            }
            UIViewController.current().present(vc, animated: true)
        }else{//没规格
            setNumberValue()
            //项目
            var dicM = getItemDic()
            dicM["totalFee"] = stringToFloat(str: self.model.fee) as AnyObject
            saveShopingCart(dic: dicM)
            //总价格
//            saveTotalFee(fee: stringToFloat(str: model.fee))
        }
        
    

    }
   
    //组件减法
    func numberReduce(number:String) {
        if(number == "0"){
            self.addLab.isHidden = false
            self.numberBtn.isHidden = true
        }
        reduceOrder(id: self.model.id)
//        reduceData(id: self.model.id)
    }
 
    
    //数据赋值
    func setData(_ model:ListCombo)
    {
        self.model = model
        titleLab.text = model.name
        priceLab.text = "$\(model.fee)"
        describeLab.text = model.illustration
        portraitImgV.setImage(with: model.imgUrl, placeholderImage: UIImage(named: "place_holder_icon"))
        if (model.isSpecs == "0"){//有规格
            specLab.text = "\(model.specsCount)个规格"
            specLab.isHidden = false
        }else{
            specLab.isHidden = true
        }
        detailBtn.isHidden = !(model.isDetails == "0")
        coverBtn.isHidden = detailBtn.isHidden
        coverBtn.isUserInteractionEnabled = !coverBtn.isHidden
//        coverBtn.backgroundColor = UIColor.red
        
        let arr = getOrderData()
        if(arr.count == 0){
            self.addLab.isHidden = false
            self.numberBtn.isHidden = true
        }else{
            var isIDKey:Bool = false
            for (_, item) in arr.enumerated() {
                if model.id == item["idkey"] as! String  {
                    let orders = item["items"] as! Array<Dictionary<String,AnyObject>>
                    let count = orders.count
                    self.numberBtn.textField.text = "\(count)"
                    isIDKey = true
                }
            }
            if isIDKey{
                self.addLab.isHidden = true
                self.numberBtn.isHidden = false
            }else{
                self.addLab.isHidden = false
                self.numberBtn.isHidden = true
            }
        }
        
    }
    
    //设置类型
    func setType(type:String) {
        self.type = type
        if(self.type == "1"){
            rootName = "日常清洁"
        }else if(self.type == "2"){
            rootName = "退房清洁"
        }else if(self.type == "3"){
            rootName = "深度清洁"
        }else if(self.type == "4"){
            rootName = "蒸汽地毯"
        }
    }
    
   
    
    // 设置数字初始值为1
    func setNumberValue() {
        self.addLab.isHidden = true
        self.numberBtn.isHidden = false
        self.numberBtn.textField.text = "\(1)"
    }
    
//    func saveTotalFee(fee:Float) {
//        if let locationFee:Float = kUserDefaults.value(forKey: kShopingCartFee) as? Float
//        {
//            let totalFee = locationFee + fee
//            kUserDefaults.setValue(totalFee, forKey: kShopingCartFee)
//            kUserDefaults.synchronize()
//        }else{
//            kUserDefaults.setValue(fee, forKey: kShopingCartFee)
//            kUserDefaults.synchronize()
//        }
//        let NotifyChatMsgRecv = NSNotification.Name(rawValue:kShopingCartNotify)
//        NotificationCenter.default.post(name: NotifyChatMsgRecv, object: nil)
//    }
    
    //规格
    func setSpecData(number:Array<AnyObject>) {
        var specs:Array<Any> = []
        var specFee:Float = 0
        for spec in number {
            let newSpec = spec as! SSSpec
            specFee = stringToFloat(str: newSpec.fee) + specFee
            let dicM = [
                    "id":"\(newSpec.id)",
                    "name":"\(newSpec.name)",
                    "fee":"\(newSpec.fee)"
            ]
            specs.append(dicM)
        }
        //存储总价格
        let totalFee:Float = (specFee + stringToFloat(str: model.fee))
//        saveTotalFee(fee: totalFee)
        var dicM = getItemDic()
        dicM["totalFee"] = totalFee as AnyObject
        dicM["listSpecs"]=specs as AnyObject
        self.saveShopingCart(dic: dicM)
    }
    
    //项目
    func getItemDic() -> Dictionary<String, AnyObject> {
        print("fushitu\(rootName)")
        let dic = [
                "id":"\(self.model.id)",
                "name":"\(self.model.name)",
                "fee":"\(self.model.fee)",
                "imgUrl":"\(self.model.imgUrl)",
                "rootName":"\(rootName)",
        ] as [String : AnyObject]
        return dic
    }
    
    //数据存储
    func saveShopingCart(dic: [String:AnyObject]) {
        
        saveOrderData(id: self.model.id, order: dic)
        
//        if var list : Array<Dictionary> = kUserDefaults.value(forKey: kShopingCartKey) as? Array<Dictionary<String, AnyObject>>
//        {
//            list.insert(dic, at: 0)
//            print("")
//            kUserDefaults.setValue(list, forKey: kShopingCartKey)
//            kUserDefaults.synchronize()
//            for item in list {
//                debugPrint("项目==",jhToJson(item))
//            }
//        }else{
//            var list: Array<Any> = []
//            list.append(dic)
//            kUserDefaults.setValue(list, forKey: kShopingCartKey)
//            kUserDefaults.synchronize()
//            print("")
//            for item in list {
//                debugPrint("项目==",jhToJson(item as! [String : AnyObject]))
//            }
//        }
//        UIViewController.current().view.makeToast("已加入购物车")
    }
   
   //进入详情
    @IBAction func detailAction(_ sender: Any) {
        let item :ListCombo =  self.model
        let vc =  SSItemDetailViewController.init(nibName: "SSItemDetailViewController", bundle: nil)
        vc.id = item.id
//        UIViewController.current().present(vc, animated: true)
        UIViewController.current().navigationController?.pushViewController(vc, animated: true)
    }
    
}





